<template>
  <div>
    <!-- 面包屑导航区域 -->
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>住房补贴申请</el-breadcrumb-item>
      <el-breadcrumb-item>当前发起补贴</el-breadcrumb-item>
    </el-breadcrumb>

    <!-- 卡片视图 -->
    <el-card>
      <div  slot="header" class="clearfix">
        <el-row style='display: flex!important;align-items: center!important;' :gutter="20">
          <el-col :span="22">
            <span style='font-size: 18px;font-weight:800'>补贴发起信息</span>
          </el-col>
          <el-col :span="4" style='display: flex!important;justify-content: right!important;'>
            <el-button type="primary" size="small" @click='showSetNameBox' :disabled='createable'>发起</el-button>
          </el-col>
        </el-row>
      </div>
      <el-table :data="currentAllowanceList" border stripe :header-cell-style="{background:'#eee',color:'#606266',fontSize: '14px'}">
            <el-table-column label="补贴名称" prop="allowanceName"></el-table-column>
            <el-table-column label="单位账号" prop="gjjzh"></el-table-column>
            <el-table-column label="补贴状态" prop="state"></el-table-column>
            <el-table-column label="使用指标文数" prop="zbwhList.length"></el-table-column>
            <el-table-column label="评论" prop="remark"></el-table-column>
            <el-table-column label="操作" width="300px">
              <template slot-scope="scope">
                <el-button size="mini" type="primary" icon="el-icon-edit" @click="revise(scope.row)" :disabled="scope.row.state === '已提交'">修改</el-button>
              </template>
            </el-table-column>
          </el-table>

    </el-card>
    <!-- 发起补贴后的补贴命名弹窗 -->
    <el-dialog title="补贴命名" :visible.sync="setNameDialogVisible" width="50%" @close="setNameDialogClosed">
      <el-form :model="setNameForm" :rules="setNameFormRules" ref="setNameFormRef" label-width="120px">
        <el-form-item label="本次补贴名称" prop="name">
          <el-input @keyup.enter.native="createAllowance" v-model="setNameForm.name"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
    <el-button @click="cancelCreateAllowance">取 消</el-button>
    <el-button type="primary"  @click="createAllowance">确 定</el-button>
  </span>
    </el-dialog>

  <!--  查看历史补贴代领信息弹窗  -->
    <el-dialog title="代领人记录信息" :visible.sync="historyDialogVisible" width="70%">
      <el-table :data="agentList" border stripe :header-cell-style="{background:'#eee',color:'#606266',fontSize: '14px'}">
        <el-table-column label="姓名" prop="dlrxm" width="100px"></el-table-column>
        <el-table-column label="身份证号" prop="dlrsfzh"></el-table-column>
        <el-table-column label="手机号" prop="phoneNumber"></el-table-column>
        <el-table-column label="卡号" prop="dllmkh" width="200px"></el-table-column>
        <el-table-column label="类型" prop="dllx" width="50px"></el-table-column>
        <el-table-column label="关系" prop="gxmc" width="50px"></el-table-column>
        <el-table-column label="代领金额" prop="dlje"></el-table-column>
        <el-table-column label="操作员" prop="czy" width="100px"></el-table-column>
        <el-table-column label="备注" prop="bz"></el-table-column>
      </el-table>
      <span slot="footer" class="dialog-footer">
        <el-button @click="historyDialogVisible=false">取 消</el-button>
        <el-button type="primary" @click="historyDialogVisible=false">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
export default {
  data() {
    return {
      // 单位账号
      gjjzh: '',
      // 所有角色列表数据
      currentAllowanceList: [],
      historyAllowanceList: [],
      // 控制分配权限对话框的显示与隐藏
      setRightDialogVisible: false,
      // 控制代领信息对话框显示隐藏
      historyDialogVisible: false,
      // 所有权限的数据
      rightslist: [],
      // 树形控件的属性绑定对象
      treeProps: {
        label: 'authName',
        children: 'children'
      },
      // 默认选中的节点Id值数组
      defKeys: [],
      // 当前即将分配权限的角色id
      roleId: '',
      date: '',
      activeName: 'now',
      createable: false,
      // 命名对话框
      setNameDialogVisible: false,
      setNameForm: {
        name: ''
      },
      // 表单验证规则
      setNameFormRules: {
        name: [
          { required: true, message: '请输入本次补贴名称', trigger: 'blur' }
        ]
      },
     // 历史补贴分页查询
      queryInfo: {
        pageSize: 10,
        pageNum: 1
      },
      // 历史补贴总条数
      total: 0,
      // 代领记录数组
      agentList: []
    }
  },
  created() {
    this.gjjzh = window.sessionStorage.getItem('gjjzh')
    this.activeName = !this.$route.query.stateInfo ? 'now' : this.$route.query.stateInfo
    this.getAllowanceList()
  },
  methods: {
    showTest() {
      console.log(1231231231)
    },
    // 获取所有补贴的列表
    async getAllowanceList() {
      let that = this
      // 1. 分页获取历史补贴数据
      this.$http.get('allowance/findAll', {emulateJSON:true, params: {
          gjjzh: this.gjjzh,
          pageNum: this.queryInfo.pageNum,
          pageSize: this.queryInfo.pageSize
        },
      }).then(function(data){
        console.log("========++++======")
        console.log('历史补贴信息',data,data.data)
        if (data.data.code !== 200) {
          return that.$message.error('获取历史补贴列表失败！')
        }
        // 1.1历史补贴数据，获取成功后赋值
        that.historyAllowanceList = data.data.data.records
        that.total = data.data.data.total
      })
      // 2. 获取当前补贴
      const { data: {code, data: currentAllowanceObj} } = await this.$http.get(`/allowance/currentAllowance?gjjzh=${this.gjjzh}`)
      if (code !== 200) return this.$message.info('当前尚未发起补贴！')
      this.currentAllowanceList.push(currentAllowanceObj)
      if(this.currentAllowanceList.length !==0) {
        // 存在当前补贴，禁用发起按钮
        this.createable = true
      }
    },
    // 根据Id删除对应的权限
    async removeRightById(role, rightId) {
      // 弹框提示用户是否要删除
      const confirmResult = await this.$confirm(
        '此操作将永久删除该补贴, 是否继续?',
        '提示',
        {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }
      ).catch(err => err)

      if (confirmResult !== 'confirm') {
        return this.$message.info('取消了删除！')
      }

      const { data: res } = await this.$http.delete(
        `roles/${role.id}/rights/${rightId}`
      )

      if (res.meta.status !== 200) {
        return this.$message.error('删除权限失败！')
      }

      // this.getRolesList()
      role.children = res.data
    },
    async handleClick(tab, event) {
      console.log(tab, event)
    },
    async revise(allowance) {
      console.log(allowance)
      this.$router.push({path: '/current', query: { gjjzh: allowance.gjjzh } })
    },
    async showAllowance(allowance) {
      console.log(allowance)
      this.$router.push({path: '/subsidiesDetails', query: { id: allowance.allowanceId, gjjzh: allowance.gjjzh} })
    },
    async deleteAllowance(allowance) {
      console.log(allowance)
      const confirmResult = await this.$confirm(
        '此操作将永久删除该指标文, 是否继续?',
        '提示',
        {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }
      ).catch(err => err)

      if (confirmResult !== 'confirm') {
        return this.$message.info('已经取消删除！')
      }
    },
    async search() {
      // date控件不选择时是空字符串,选择了是数组，长度为2
      if (!this.date) return this.$message.warning('请指定查询时间范围 ！')
      let sdate = this.date[0].getFullYear() + '-' + ((this.date[0].getMonth() + 1 + '') .padStart(2, '0')) + '-' + ((this.date[0].getDate()+ '').padStart(2, '0'))
      let edate = this.date[1].getFullYear() + '-' + ((this.date[1].getMonth() + 1 + '').padStart(2, '0')) + '-' + ((this.date[1].getDate() + '').padStart(2, '0'))
      let that = this
      // 1. 分页获取历史补贴数据
      this.$http.get('allowance/findAll', {emulateJSON:true, params: {
          gjjzh: this.gjjzh,
          pageNum: this.queryInfo.pageNum,
          pageSize: this.queryInfo.pageSize,
          startDate: sdate,
          endDate: edate
        },
      }).then(function(data){
        console.log("========++++======")
        console.log('历史补贴信息',data,data.data)
        if (data.data.code !== 200) {
          return that.$message.error('指定时间内未查询到相关补贴信息！')
        }
        // 1.1历史补贴数据，获取成功后赋值
        that.historyAllowanceList = data.data.data.records
        that.total = data.data.data.total
        that.$message.success('查询成功！')
      })
    },
    async clearSearch() {
      this.date = ''
    },
    // 展示命名对话框
    showSetNameBox() {
      this.setNameDialogVisible = true
    },
    cancelCreateAllowance() {
      this.setNameDialogVisible = false
      this.$message.info('本次补贴发起已取消~')
    },
    // 监听命名对话框的关闭事件
    setNameDialogClosed() {
    this.$refs.setNameFormRef.resetFields()
    },
    async createAllowance() {
      this.$refs.setNameFormRef.validate( valid => {
        if (!valid) return this.$message.error('请填写本次补贴名称')
        //验证通过执行逻辑
        this.setNameDialogVisible = false
        let that = this
        let gjjzh = window.sessionStorage.getItem('gjjzh')
        console.log(gjjzh)
        this.$http.get('allowance/createAllowance', { params: { allowanceName: this.setNameForm.name, gjjzh: gjjzh } }, {emulateJSON:true}).then(function(data){
          console.log('发起补贴',data.data)
          if (data.data.code !== 200) return that.$message.error('补贴发起失败')
          that.$message.success('补贴发起成功')
          that.getAllowanceList()
        })
      })
    },
    // 监听历史补贴页码大小
    handleSizeChange(newSize) {
      this.queryInfo.pageSize = newSize
      this.getAllowanceList()
    },
    // 监听当前页码变化值
    handleCurrentChange(newNum) {
      this.queryInfo.pageNum = newNum
      this.getAllowanceList()
    },
    // 代领信息对话框显示与隐藏
    async showHistoryDialog(queryObj) {
      // 获取代领信息
      const { data: res } = await this.$http.get('/allowance/findAllDlrlistOfBtlist', { params: {
          btcode: queryObj.btcode,
          zbwh: queryObj.zbwh,
          zgbh: queryObj.zgbh
        }})
      if (res.code !== 200) return this.$message.warning('没有对应的代领记录信息！')

      console.log('代领信息',res.data)
      this.agentList = res.data
      this.historyDialogVisible = true
    }
  }
}
</script>

<style lang="less" scoped>
.el-tag {
  margin: 7px;
}

.bdtop {
  border-top: 1px solid #eee;
}

.bdbottom {
  border-bottom: 1px solid #eee;
}

.vcenter {
  display: flex;
  align-items: center;
}
</style>
